import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import POSConnect from "@/pages/subReportForm/print-config/POSConnect";
import { cashiersTemplate, fields } from "@/pages/subReportForm/print-config/template";

type ticketType = "cashier" | "kitchen";

const ticketKeyName = {
  cashier: "currentFrontTemplateId",
  kitchen: "currentRearTemplateId",
};

/** 打印机设置 */
const print = {
  namespaced: true,
  state: uni.getStorageSync("__APP__printModule") || {
    /** 1 为开启， 2 为不开启 */
    // 是否开启前台打票
    frontDeskPrinting: "1",
    //是否开启后厨打票
    rearKitchenPrinting: "2",
    // 当前打印模板id
    // currentTemplateId: "1",
    // // 当前前台打印模板id 1 为默认模板， 其他模板增量+1
    currentFrontTemplateId: "1",
    // 当前前后台打印模板id
    currentRearTemplateId: "1",
    // 模板库
    printTemplate: cashiersTemplate,
    // usb打印机状态 （0 初始化未完成（或者失败），1 初始化成功）
    usbPrinterStatus: 0,
    // 已连接的打印机列表（存本地，每次初始化后更新）
    usbPrinterList: [],
  },
  actions: {
    // 初始化usb打印机
    async usbPrinterInit({ commit, dispatch, state }) {
      console.debug("store/usbPrinterInit");
      try {
        // 初始化打印机器
        await asyncExecFunction("KoInitPrinter");

        // 获取打印机列表 并 连接上第一个打印机
        await dispatch("usbPrinterUpdateList");
        state.usbPrinterStatus = 1;
        console.warn("打印机初始化成功");
        uni.setStorageSync("__APP__printModule", state);
      } catch (error) {
        state.usbPrinterStatus = 0;
        console.warn("打印机初始化失败", error);
      }
    },
    // 更新打印机列表
    async usbPrinterUpdateList({ commit, dispatch, state }) {
      // 获取打印机列表
      const devicesJson = await asyncExecFunction("KoGetUsbPrinterList");
      const devices = JSON.parse(devicesJson);
      console.log("store/usbPrinterInit - devices ", devices);
      state.usbPrinterList = Object.keys(devices).map((key, index) => {
        const device = devices[key];
        return {
          id: device.DeviceId,
          path: device.DeviceName,
          name: device.DeviceName,
          serialNumber: device.SerialNumber,
          printSize: "",
          purpose: updatePurpose(state, device.SerialNumber, index),
          printerType: "usb",
          status: "success",
          statusText: "已连接",
          details: device,
        };
      });

      // 自动连接上第一个打印机
      if (state.usbPrinterList.length > 0) {
        const firstPrinter = state.usbPrinterList[0];
        // 创建连接
        const createResult = await asyncExecFunction("KoCreatePrinter", {
          DeviceType: POSConnect.DEVICE_TYPE_USB,
          DevicePath: firstPrinter.path,
        });
        console.log("createResult>", createResult);
      }
    },
  },
  mutations: {
    /** 设置 打印模式 && 打印模板  */
    setPrintModule(state: any, data: any) {
      if (!data) return;
      const { frontDeskPrinting, rearKitchenPrinting, printTemplate, currentTemplateId } = data;
      if (frontDeskPrinting) state.frontDeskPrinting = frontDeskPrinting;
      if (rearKitchenPrinting) state.rearKitchenPrinting = rearKitchenPrinting;
      if (printTemplate && Array.isArray(printTemplate)) state.printTemplate = printTemplate;
      // if (currentTemplateId) state.currentTemplateId = currentTemplateId;
      uni.setStorageSync("__APP__printModule", state);
    },
    /** 使用打印模板（设置id） */
    useTemplate(state: any, { id, type }: { id: string; type: ticketType }) {
      // 判断 id 是否有效
      if (!id) return;
      if (!state.printTemplate.find((item: any) => item.id == id)) return;

      // state.currentTemplateId = id;
      const keyName = ticketKeyName[type];
      state[keyName] = id;
      uni.setStorageSync("__APP__printModule", state);
    },
    /** 添加打印模板 (自动添加id) */
    addTemplateByData(state: any, data: { useFields: string[]; type: ticketType }) {
      if (!data || !Array.isArray(data)) return;
      state.printTemplate.push({
        id: state.printTemplate.length + 1,
        type: data.type,
        useFields: data.useFields,
      });
      uni.setStorageSync("__APP__printModule", state);
    },
    /** 添加打印模板,以默认模板 (自动添加id) */
    addTemplateByModule(state: any, ticketType: ticketType) {
      // 找到默认模板（id=1）的字段
      const data = state.printTemplate.find((item: any) => item.id == 1).useFields;
      state.printTemplate.push({
        id: state.printTemplate.length + 1,
        type: ticketType,
        useFields: data,
      });
      uni.setStorageSync("__APP__printModule", state);
    },
    /** 删除打印模板 */
    deleteTemplate(state: any, id: string) {
      if (!id) return;
      const index = state.printTemplate.findIndex((item: any) => item.id == id);
      if (index !== -1) state.printTemplate.splice(index, 1);
      uni.setStorageSync("__APP__printModule", state);
    },
    /** 修改打印模板 */
    updateTemplate(state: any, data: { id: string; useFields: string[] }) {
      if (!data || !Array.isArray(data)) return;
      const index = state.printTemplate.findIndex((item: any) => item.id == data.id);
      if (index !== -1) state.printTemplate[index] = data;
      uni.setStorageSync("__APP__printModule", state);
    },
    // 修改打印模板的字段是否使用  isUsed: true
    editTemplateField(state: any, data: { name: string; isUsed: boolean; type: ticketType; fixedValue?: string }) {
      // console.log(data, "data");
      if (!data) return;
      // 通过数据源 fields 修改打印模板的字段是否使用， 然后重新生成存储
      const newSaveFieldValues = [];

      const keyName = ticketKeyName[data.type];
      const currId = state[keyName];
      const currentTemplate = state.printTemplate.find((item: any) => item.id == currId);
      // const newFields = JSON.parse(JSON.stringify(currentTemplate.useFields));

      // 双层循环， 修改打印模板的字段是否使用
      for (const group of fields) {
        for (const f of group.fields) {
          if (f.name == data.name) {
            f.isUsed = data.isUsed;
          }
          if (f.isUsed) newSaveFieldValues.push(f.name);
        }
      }
      // 修改当前打印模板的字段信息
      if (currentTemplate) {
        currentTemplate.useFields = newSaveFieldValues;
      }
      // 修改当前打印模板的固定字段值信息
      if (data.fixedValue) {
        currentTemplate.fixedValue = data.fixedValue;
      }

      // 并且重新生成
      uni.setStorageSync("__APP__printModule", state);
    },
    // 修改当前模板的某些字段固定值
    editTemplateFixedValue(state: any, data: { id: string; fixedValue: { name: string; fixed: string } }) {
      if (!data) return;
      const currentTemplate = state.printTemplate.find((item: any) => item.id == data.id);
      if (currentTemplate) {
        // 如果 fixedConfig 不存在，则创建
        if (!currentTemplate.fixedConfig) {
          currentTemplate.fixedConfig = [];
        }
        // 查找是否有相同的字段, 如果有，则修改，没有则添加
        const index = currentTemplate.fixedConfig.findIndex((item: any) => item.name == data.fixedValue.name);
        if (index !== -1) {
          currentTemplate.fixedConfig[index] = data.fixedValue;
        } else {
          currentTemplate.fixedConfig.push(data.fixedValue);
        }
      }
      uni.setStorageSync("__APP__printModule", state);
    },
    // ------- 设备 ------
    // 修改设备所属区域
    updatePrintArea(state: any, device: any) {
      // 更新   state.usbPrinterList
      if (!device) return;
      const printer = state.usbPrinterList.find(
        (item: any) => item.details.SerialNumber == device.details.SerialNumber
      );
      printer.purpose = device.purpose;
      uni.setStorageSync("__APP__printModule", state);
    },
    clear(state: any) {
      // 清除数据
      const clearKeys = Object.keys(state);
      clearKeys.forEach((key) => {
        const keyName = "__APP__" + key;
        state[keyName] = {};
        uni.removeStorageSync(keyName);
      });
    },
  },
  getters: {
    printModule: (state: any) => {
      return {
        frontDeskPrinting: state.print.frontDeskPrinting,
        rearKitchenPrinting: state.print.rearKitchenPrinting,
      };
    },
    printTemplate: (state: any) => {
      return state.print.printTemplate;
    },
    // currentTemplateId: (state: any) => {
    //   return state.print.currentTemplateId;
    // },
    currentFrontTemplateId: (state: any) => {
      return state.print.currentFrontTemplateId;
    },
    currentRearTemplateId: (state: any) => {
      return state.print.currentRearTemplateId;
    },
    // // 获取当前打印模板
    // currentTemplate: (state: any) => {
    //   return state.print.printTemplate.find((item: any) => item.id == state.print.currentTemplateId);
    // },
    // 获取当前（前台）打印模板
    currentFrontTemplate: (state: any) => {
      return state.print.printTemplate.find((item: any) => item.id == state.print.currentFrontTemplateId);
    },
    // // 获取当前（后台）打印模板
    currentRearTemplate: (state: any) => {
      return state.print.printTemplate.find((item: any) => item.id == state.print.currentRearTemplateId);
    },
    // 当前打印模板的字段
    // currentTemplateUseFields: (state: any) => {
    //   const current = state.print.printTemplate.find((item: any) => item.id == state.print.currentTemplateId);
    //   return current ? current.useFields : fields;
    // },
    // 当前（前台）打印模板的字段
    currentFrontTemplateUseFields: (state: any) => {
      const current = state.print.printTemplate.find((item: any) => item.id == state.print.currentFrontTemplateId);
      // return current ? current.useFields : ['goodslist'];
      return current || { id: -1, type: "cashier", useFields: ["goodslist"] };
    },
    // 当前（后台）打印模板的字段
    currentRearTemplateUseFields: (state: any) => {
      const current = state.print.printTemplate.find((item: any) => item.id == state.print.currentRearTemplateId);
      return current ? current.useFields : ["goodslist"];
    },
    // 根据模板id 查找模板数据
    findTemplateById: (state: any) => (id: number) => {
      return state.print.printTemplate.find((item: any) => item.id == id);
    },
    // 获取usb打印机的状态
    usbPrinterStatus: (state: any) => {
      return state.print.usbPrinterStatus;
    },
    // 获取本地usb打印机列表
    usbPrinterList: (state: any) => {
      return state.print.usbPrinterList;
    },
    // 获取usb打印机列表中  purpose:["前台"] 包含前台打印的
    usbPrinterListFront: (state: any) => {
      return state.print.usbPrinterList.filter((item: any) => {
        return Array.isArray(item.purpose) && item.purpose.includes("前台");
      });
    },
    // 获取usb打印机列表中  purpose:["后厨"] 包含后厨打印的
    usbPrinterListRear: (state: any) => {
      return state.print.usbPrinterList.filter((item: any) => {
        return Array.isArray(item.purpose) && item.purpose.includes("后厨");
      });
    },
  },
};

// 从 state.usbPrinterList 中查找 .details.SerialNumber 相同的
// 并将其 .purpose 配置为 当前项的 .purpose
function updatePurpose(state: any, SerialNumber: string, index: number) {
  if (!Array.isArray(state.usbPrinterList)) {
    state.usbPrinterList = [];
    return index == 0 ? ["前台", "后厨"] : [];
  } else {
    if (state.usbPrinterList.length == 0 && index == 0) {
      return ["前台", "后厨"];
    }
    const printer = state.usbPrinterList.find((item: any) => item.details.SerialNumber == SerialNumber);
    if (Array.isArray(printer?.purpose) && printer.purpose.length > 0) {
      return printer.purpose;
    }
    return [];
  }
}

export default print;
